package com.bird.extension.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @Author: sijunqiang
 * @Date: 2020/4/4 18:00
 * @Description: user reflect to get object inner member value and modify value
 */
public class FieldCollector {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        // get big  Class object
        Class clazzField = Class.forName("com.bird.extension.reflect.ReflectTarget");

        // 1: get all public field
        System.out.println("*********** get all public field ***********************");
        Field[] fieldArray = clazzField.getFields();
        for (Field field : fieldArray) {
            System.out.println(field);
        }

        // 2: get all field
        System.out.println("**********get all field ***************");
        Field[] declaredFields = clazzField.getDeclaredFields();
        for (Field field : declaredFields) {
            System.out.println(field);
        }

        //3: get the single specific public field and invokes it
        System.out.println("************** get the single specific public field and invokes it *********************");
        Field field = clazzField.getField("name");
        System.out.println("print the public field name=" + field);
        Constructor constructor = clazzField.getConstructor();
        ReflectTarget reflectTarget = (ReflectTarget) constructor.newInstance();
        field.set(reflectTarget, "hello this is the first my reflect ");
        System.out.println("check the value field name=" + reflectTarget.name);

        //4: get the single private field and invokes it
        System.out.println("****************get the single private field and invokes it **************");
        Field singlePrivateField = clazzField.getDeclaredField("targetInfo");
        System.out.println(singlePrivateField);
        singlePrivateField.setAccessible(true);
        singlePrivateField.set(reflectTarget, "18321682661");
        System.out.println("check the information "+ reflectTarget);
    }

}
